﻿#include<iostream>
#include"ConcurrentAlloc.h"

//void TestIndexAndRoundUp()
//{
//	// 从1-10000尝试
//	int n = 10000;
//
//	for (int i = 1; i <= 256*1024; i++)
//	{
//		if (SizeClass::Index(i) != SizeClass2::Index(i) ||
//			SizeClass::RoundUp(i) != SizeClass2::RoundUp(i))
//		{
//			cout << "数字为:" << i << endl;
//			cout << "方法一：" << SizeClass::Index(i) << " :" << SizeClass::RoundUp(i) << endl;
//			cout << "方法二：" << SizeClass2::Index(i) << " :" << SizeClass2::RoundUp(i) << endl;
//			cout << "验证错误" << endl;
//			exit(1);
//		}
//
//	}
//
//}


void alloc1()
{
	for (int i = 0; i < 3; i++)
	{
		ConcurrentAlloc(7);
	}
}

void alloc2()
{
	for (int i = 0; i < 3; i++)
	{
		ConcurrentAlloc(8);
	}
}

void TestThreadConcurrent()
{
	std::thread t1(alloc1);
	std::thread t2(alloc2);

	t1.join();
	t2.join();
}



void TestConcurrentAlloc()
{
	//void*p1=ConcurrentAlloc(1);
	//void*p2=ConcurrentAlloc(7);
	//void*p3=ConcurrentAlloc(4);
	//

	//cout << p1 << endl;
	//cout << p2 << endl;
	//cout << p3 << endl;
	//cout << p4 << endl;


	for (int i = 0; i < 1024; i++)
	{
		void* p = ConcurrentAlloc(6);
	}
	void* p = ConcurrentAlloc(6);
}

void TestFree()
{
	void* p1 = ConcurrentAlloc(6);
	void* p2 = ConcurrentAlloc(7);
	void* p3 = ConcurrentAlloc(4);
	void* p4 = ConcurrentAlloc(5);
	void* p5 = ConcurrentAlloc(5);
	void* p6 = ConcurrentAlloc(5);
	void* p7 = ConcurrentAlloc(5);
	void* p8 = ConcurrentAlloc(5);


	ConcurrentFree(p1);
	ConcurrentFree(p2);
	//ConcurrentFree(p3, 4);
	//ConcurrentFree(p4, 5);
	//ConcurrentFree(p5, 5);
	//ConcurrentFree(p6, 5);
	//ConcurrentFree(p7, 5);
	//ConcurrentFree(p8, 5);
}

void TestSpanSplit()
{
	span* newSpan = new span;
	newSpan->_freeList = SystemAlloc(1);
	size_t size = 8;

	char* start = (char*)newSpan->_freeList;
	char* end = start + (size*3);
	
	while (start < end)
	{
		Next(start) = start + size;
		start += size;  // 加的应当是对齐后的大小
	}
	Next(end - size) = nullptr;


	//计算实际分割个数
	size_t realNum = 1;
	start = (char*)newSpan->_freeList;
	end = start;

	int batchNum = 4;
	// 不断向后移动
	for (int i = 0; i < batchNum - 1 && Next(end); i++)
	{
		realNum++;
		end = (char*)Next(end);
	}

	// 处理span剩下的内存
	newSpan->_freeList = Next(end);
	Next(end) = nullptr;
	newSpan->_useCount += realNum; // 该span使用了多少个对象

}



//int main()
//{
//	//cout << sizeof(node);
//	//TestObjectPool();
//
//	//TestIndexAndRoundUp();
//	//TestThreadConcurrent();
//
//	//TestConcurrentAlloc();
//
//
//	//TestFree();
//
//	TestSpanSplit();
//
//
//	return 0;
//}